'use strict';
const db = uniCloud.database();
const rooms = db.collection('rooms');
const gameRecords = db.collection('game_records');

// 存储WebSocket连接
const connections = new Map();

// WebSocket连接事件
exports.onWebsocketConnection = async function(event) {
  console.log("WebSocket连接建立", event);
  const { connectionId, query } = event;
  const { roomId, openId } = query;
  
  try {
    // 保存连接
    if (!connections.has(roomId)) {
      connections.set(roomId, new Map());
    }
    connections.get(roomId).set(openId, connectionId);
    
    // 获取房间成员
    const room = await rooms.doc(roomId).get();
    if (!room.data || room.data.length === 0) {
      throw new Error('房间不存在');
    }
    
    // 广播新成员加入消息
    broadcastToRoom(roomId, {
      type: 'memberJoin',
      payload: {
        openId,
        members: room.data[0].members
      }
    }, openId);
  } catch (error) {
    console.error('WebSocket连接处理失败:', error);
  }
};

// WebSocket消息事件
exports.onWebsocketMessage = async function(event) {
  console.log("收到WebSocket消息", event);
  const { connectionId, payload } = event;
  
  try {
    const message = JSON.parse(payload);
    const { type, data } = message;
    
    if (type === 'payment') {
      const { roomId, payerOpenId, payeeOpenId, amount } = data;
      
      // 更新游戏记录
      const record = await gameRecords.add({
        roomId,
        payerOpenId,
        payeeOpenId,
        amount,
        createTime: Date.now()
      });
      
      // 更新房间成员积分
      const room = await rooms.doc(roomId).get();
      const members = room.data[0].members.map(member => {
        if (member.openId === payerOpenId) {
          member.score -= amount;
        } else if (member.openId === payeeOpenId) {
          member.score += amount;
        }
        return member;
      });
      
      await rooms.doc(roomId).update({
        members
      });
      
      // 广播支付消息
      broadcastToRoom(roomId, {
        type: 'payment',
        payload: {
          record: record.id,
          members
        }
      });
    }
  } catch (error) {
    console.error('WebSocket消息处理失败:', error);
  }
};

// WebSocket断开事件
exports.onWebsocketDisConnection = async function(event) {
  console.log("WebSocket连接断开", event);
  const { connectionId } = event;
  
  for (const [roomId, roomConnections] of connections.entries()) {
    for (const [openId, connId] of roomConnections.entries()) {
      if (connId === connectionId) {
        roomConnections.delete(openId);
        if (roomConnections.size === 0) {
          connections.delete(roomId);
        }
        break;
      }
    }
  }
};

// 广播消息到房间
function broadcastToRoom(roomId, message, excludeOpenId = null) {
  if (connections.has(roomId)) {
    const roomConnections = connections.get(roomId);
    const ws = uniCloud.webSocketServer();
    
    roomConnections.forEach((connectionId, openId) => {
      if (openId !== excludeOpenId) {
        ws.send(connectionId, JSON.stringify(message));
      }
    });
  }
} 